//
//  ViewController.swift
//  Giraffe
//
//  Created by zyq on 2018/11/21.
//  Copyright © 2018 Mutsu. All rights reserved.
//

import UIKit
import WebKit

class ViewController: UIViewController {
    var contentView: UIView!
    var textView: UITextView!
    var switchBtn: UIButton!
    var notepad: Notepad!
    var webView: WKWebView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        var contentRect = view.bounds
        contentRect.size.height -= 100
        contentView = UIView.init(frame: contentRect)
        self.view.addSubview(contentView)
        
        notepad = Notepad(frame: contentView.bounds, themeFile: "one-dark")
        contentView.addSubview(notepad)
        
        webView = WKWebView.init(frame: contentView.bounds)
        contentView.addSubview(webView)
        webView.isHidden = true
        
        notepad.text = """
        ## Try CommonMark
        
        You can try CommonMark here.  This dingus is powered by
        [js](https://github), the
        JavaScript reference implementation.
        
        Here's our logo (hover to see the title text):
        
        Inline-style:
        ![alt text](https://github.com/adam-p/markdown-here/raw/master/src/common/images/icon48.png)
        
        1. item one
        2. item two
        - sublist
        - sublist
        
        > Here is comments
        """
        
        switchBtn = UIButton.init(frame: CGRect.init(x: 0, y: contentRect.size.height, width: 40, height: 40))
        view.addSubview(switchBtn)
        switchBtn.setTitle("预览", for: .normal)
        switchBtn.setTitleColor(.black, for: .normal)
        switchBtn.addTarget(self, action: #selector(switchBtnTapped), for: .touchUpInside)
    }
    
    @objc func switchBtnTapped() {
        webView.isHidden = !webView.isHidden
        switchBtn.setTitle(webView.isHidden ? "预览" : "编辑", for: .normal)
        
        let renderedMDCText = cmark_markdown_to_html(notepad.text, notepad.text.count, 0)
        var renderedHTMLText = String.init(cString:renderedMDCText!)
        
        let style = "<style> body { color: purple; } h2 { color: green; } </style>"
        
        renderedHTMLText = "<html><head>\(style)</head><body>\(renderedHTMLText)</body></html>"
        
        webView.loadHTMLString(renderedHTMLText, baseURL: nil)
    }
}

